package com.ophiux.micro.core.infrastructure.page;

import java.util.List;

import com.ophiux.micro.core.domain.page.MyPage;
import com.ophiux.micro.core.domain.page.Page;
import com.ophiux.micro.core.domain.page.PageConfig;
import com.ophiux.micro.core.domain.page.repository.IPageRepository;
import com.ophiux.utils.exception.OphiuxRepositoryException;

/**
 * 分页查询工厂
 * @author chenh	2018-11-07 chenh
 *
 */
public class PageRepositoryFactoryBean {

	private PageRepositoryFactoryBean() {}
	
	/**
	 * 单例模式，保证只会创建一次
	 * @author chenh
	 *
	 */
	private static class PageRepositoryFactoryBeanBuilder{
		private final static PageRepositoryFactoryBean instance = new PageRepositoryFactoryBean();
	}
	
	public static PageRepositoryFactoryBean instance() {
		return PageRepositoryFactoryBeanBuilder.instance;
	}
	
	/**
	 * 查询分页数据
	 * @param repository	数据分页查询仓储
	 * @param config	查询配置，含分页信息及查询条件
	 * @return
	 * @throws OphiuxRepositoryException 
	 */
	public <T> Page<T> queryPageData(IPageRepository<T> repository , PageConfig config) throws OphiuxRepositoryException{
		
		//查询满足条件的总数量
		int totalCount = repository.selectTotalCount(config);
		
		int pageIndex = config.getPageIndex();
		int pageSize = config.getPageSize();
		
		Page<T> page = new MyPage<T>(pageIndex, pageSize , totalCount);
		
		//查询数据   --根据分页配置查询
		List<T> content = repository.selectPageData(config);
		
		//同时设置分页内容及实际量
		page.setPageContent(content);
		
		return page;
	}
	
	/**
	 * 获取分页数据
	 * @param repository
	 * @param config
	 * @return
	 * @throws OphiuxRepositoryException
	 */
	public <T> Page<T> queryPageData(IPageDataReader<T> reader , PageConfig config) throws OphiuxRepositoryException{
		
		//查询满足条件的总数量
		int totalCount = reader.GetTotalCount(config);
		
		int pageIndex = config.getPageIndex();
		int pageSize = config.getPageSize();
		
		Page<T> page = new MyPage<T>(pageIndex, pageSize , totalCount);
		
		//查询数据   --根据分页配置查询
		List<T> content = reader.GetPageDatas(config);
		
		//同时设置分页内容及实际量
		page.setPageContent(content);
		
		return page;
	}
	
	/**
	 * 分页数据读取
	 * @author chenh
	 *
	 */
	public interface IPageDataReader<T>{
		
		/**
		 * 分页数据
		 * @return
		 */
		public List<T> GetPageDatas(PageConfig config) throws OphiuxRepositoryException;
		
		/**
		 * 总数量
		 * @return
		 */
		public int GetTotalCount(PageConfig config) throws OphiuxRepositoryException;
		
	}
	
}
